package com.wz.netty;

import java.nio.charset.Charset;

import com.mchange.lang.CharUtils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class ClientHandler extends ChannelInboundHandlerAdapter{
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("cli-channelInactive");
		super.channelInactive(ctx);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf m = (ByteBuf) msg; // (1)  
        try {
        	System.out.println(m.toString(Charset.forName("GBK")));
//            ctx.close();  
        } finally {
            m.release();
        }
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		System.out.println("cli-channelReadComplete");
		super.channelReadComplete(ctx);
	}

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		System.out.println("cli-channelRegistered");
		super.channelRegistered(ctx);
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		System.out.println("cli-channelUnregistered");
		super.channelUnregistered(ctx);
	}

	@Override
	public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
		System.out.println("cli-channelWritabilityChanged");
		super.channelWritabilityChanged(ctx);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		System.out.println("cli-userEventTriggered");
		super.userEventTriggered(ctx, evt);
	}

	@Override  
    public void channelActive(final ChannelHandlerContext ctx) { // (1)  
		System.out.println("cli-channelActive");
    	ByteBuf buf = ctx.alloc().buffer(128);
    	buf.writeInt(123);
//    	final ChannelFuture f = ctx.writeAndFlush(buf);
    	ctx.writeAndFlush(buf);
		
//        time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));  
//  
//        final ChannelFuture f = ctx.writeAndFlush(time); // (3)  
//        f.addListener(new ChannelFutureListener() {  
//            @Override  
//            public void operationComplete(ChannelFuture future) {  
//                ctx.close();  
//            }  
//        }); // (4)  
    }
  
    @Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {  
        cause.printStackTrace();
        System.out.println("error");
        ctx.close();  
    }
}
